﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Example05.aspx.cs" Inherits="Chapter32.Example05" %>

<!DOCTYPE html>

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>代码清单 32-5 处理 Ajax 错误</title>
    <meta name="author" content="Adam Freeman" />
    <meta name="description" content="A simple example" />
    <link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
</head>
<body>
    <div>
        <button>Example01.Apples</button>
        <button>Example01.Cherries</button>
        <button>Example01.Bananas</button>
        <button>Cucumber</button>
        <button id="badhost">Bad Host</button>
        <button id="badurl">Bad URL</button>
    </div>
    <div id="target">Press a button</div>
    <div id="errormsg"></div>
    <div id="statusmsg"></div>
    <script>
        var buttons = document.getElementsByTagName("button");
        for (var i = 0; i < buttons.length; i++) {
            buttons[i].onclick = handleButtonPress;
        }

        function handleButtonPress(e) {
            clearMessages();
            var httpRequest = new XMLHttpRequest();
            httpRequest.onreadystatechange = handleResponse;
            httpRequest.onerror = handleError;
            try {
                switch (e.target.id) {
                    case "badhost":
                        httpRequest.open("GET", "http://a.modomain/doc.html");
                        break;

                    case "badurl":
                        httpRequest.open("GET", "http://");
                        break;

                    default:
                        httpRequest.open("GET", e.target.innerHTML + ".aspx");
                        break;
                }
                httpRequest.send();
            } catch (error) {
                displayErrorMsg("try/catch", error.message);
            }
        }

        function handleResponse(e) {
            if (e.target.readyState == e.target.DONE && e.target.status == 200) {
                document.getElementById("target").innerHTML = e.target.responseText;
            } else if (e.target.readyState == e.target.DONE) {
                document.getElementById("statusmsg").innerHTML = "Status: " + e.target.status + " " + e.target.statusText;
            }
        }

        function handleError(e) {
            displayErrorMsg("Error event", e.target.status + e.target.statusText);
        }

        function displayErrorMsg(src, msg) {
            document.getElementById("statusmsg").innerHTML = src + ": " + msg;
        }

        function clearMessages() {
            document.getElementById("errormsg").innerHTML = "";
            document.getElementById("statusmsg").innerHTML = "";
        }
    </script>
</body>
</html>
